﻿namespace Groundwork.Extensions
{
    using System;

    /// <summary>
    /// Character Encoding Extensions
    /// </summary>
    public static class Encodings
    {
        /// <summary>
        /// converts the base64 encoded string back into human readable format
        /// </summary>
        /// <param name="dataToDecode">string to decode</param>
        /// <returns>Decoded string</returns>
        /// <exception cref="System.ArgumentNullException">dataToDecode is null or an empty string</exception>
        /// <example>
        ///   <code>
        ///   <![CDATA[
        /// string myString = "hello world";
        /// string encodedString = myString.EncodeToBase64();
        /// string decodedString = encodedString.DecodeFromBase64();
        /// ]]>
        ///   </code>
        ///   </example>
        public static string DecodeFromBase64(this string dataToDecode)
        {
            dataToDecode.ThrowIfNullOrEmpty();
            byte[] encodedDataAsBytes = Convert.FromBase64String(dataToDecode);
            return System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);
        }

        /// <summary>
        /// converts a human readable string into a bas64 encoded string
        /// </summary>
        /// <param name="datatoEncode">value to encode</param>
        /// <returns>encoded string</returns>
        /// <exception cref="System.ArgumentNullException">dataToDecode is null or an empty string</exception>
        /// <example>
        ///   <code>
        ///   <![CDATA[
        /// string myString = "hello world";
        /// string encodedString = myString.EncodeToBase64();
        /// ]]>
        ///   </code>
        ///   </example>
        public static string EncodeToBase64(this string datatoEncode)
        {
            datatoEncode.ThrowIfNullOrEmpty();
            byte[] toEncodeAsBytes = System.Text.Encoding.UTF8.GetBytes(datatoEncode);
            return System.Convert.ToBase64String(toEncodeAsBytes);
        }
    }
}